package team.nmsg.visualchassis.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.swing.filechooser.FileSystemView;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import team.nmsg.visualchassis.service.IVisualChassisService;

@Service
public class VisualChassisServiceImpl implements IVisualChassisService{
	public static FileSystemView fsv = FileSystemView.getFileSystemView();
	public static File homeDirectory = fsv.getHomeDirectory();

	private static final Logger logger = LoggerFactory.getLogger(VisualChassisServiceImpl.class);
	
	@Override
	public Map<String, String> createChassis(JSONObject chassis){
		Map<String, String> fileMap = new HashMap();
		try {
			JSONObject shelf = chassis.getJSONObject("shelf");
			if(shelf != null){
				Document shelfDot = DocumentHelper.parseText(shelf.getString("shelfXml"));
				saveXMLToPath(shelfDot, shelf.getString("shelfName"), fileMap);
			}
			
			JSONArray cards = chassis.getJSONArray("cards");
			for(Object obj : cards){
				JSONObject card = JSONObject.parseObject(obj.toString());
				Document cardDot = DocumentHelper.parseText(card.getString("cardXml"));
				saveXMLToPath(cardDot, card.getString("cardName"), fileMap);
			}
		} catch (Exception e) {
			logger.error("", e);
			return fileMap;
		}
		return fileMap;
	}
	public static void saveXMLToPath(Document document,String name, Map<String, String> fileMap) throws Exception{
        OutputFormat format = new OutputFormat("	",true);  
        format.setEncoding("UTF-8");//设置编码格式  
        String chassisPath =System.getProperty("user.dir")
				+ "/resources/NMSChassisConfig/";
//        String path = homeDirectory.getAbsolutePath()+"/"+name+".xml";
        if(!new File(chassisPath).isFile()){
        	new File(chassisPath).mkdirs();
        }
        String path = chassisPath + name + ".xml";
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path),format);  
        xmlWriter.write(document);
        xmlWriter.close();
        
        fileMap.put(name + ".xml", path);
	}

	
	

}
